// PlayerManager.js
import { _decorator, Component, Node, director, Director, SceneAsset } from 'cc';
import { Player } from '../Player';
import Singleton from '../utils/Singleton';
import EventManager from './EventManager';
import DataManager from '../global/DataManager';
// import { EventManager } from './EventManager';
const { ccclass, property } = _decorator;
export class ConnectionManager extends Singleton {
    webSocket: WebSocket;
    private ws: WebSocket = null;
    private url: string = 'ws://127.0.0.1:7890';
    static get Instance() {
        return super.GetInstance<ConnectionManager>();
    }
    connect() {
        this.ws = new WebSocket(this.url);

        this.ws.onopen = () => {
            console.log('WebSocket connected');
            // EventManager.Instance.emit('ws-connected');
        };

        this.ws.onmessage = (event) => {

            // EventManager.getInstance().emit('ws-message', data);

            const { data, url, success, message } = JSON.parse(event.data)
            console.log(data, url, success, message);

            if (success) {
                switch (url) {
                    case 'login':
                        console.log(123456);
                        DataManager.Instance.player = { ...data }
                        director.loadScene("scene");
                        break;

                    default:
                        break;
                }
            }


        };

        this.ws.onclose = () => {
            console.log('WebSocket disconnected');
            // EventManager.getInstance().emit('ws-disconnected');
        };

        this.ws.onerror = (error) => {
            console.error('WebSocket error', error);
            // EventManager.getInstance().emit('ws-error', error);
        };
    }

    send(message: object) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify(message));
        }
    }

}
